package com.chengww.grab_rp.activities

import androidx.lifecycle.MutableLiveData
import com.chengww.grab_rp.api.LogoutResponse
import com.chengww.grab_rp.api.NetworkManager
import com.chengww.grab_rp.api.PluginService
import com.chengww.grab_rp.api.RequestBody
import com.chengww.grab_rp.base.BaseViewModel
import com.chengww.grab_rp.database.AppDatabase
import com.chengww.grab_rp.database.user.UserDao
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/**
 * Created by chengww on 2/20/21
 * @author chengww
 */
class HomeViewModel(private val userDao: UserDao, private val appDatabase: AppDatabase) : BaseViewModel() {

    private val service: PluginService by lazy { NetworkManager.pluginService }

    val logoutResponse = MutableLiveData<LogoutResponse>()
    val userLive = userDao.getUserLive()
    val version = MutableLiveData<String>()

    fun logout() {
        launch(null, {
            val user = userDao.getUser()
            if (user == null) {
                val response = LogoutResponse(0, "退出登录成功")
                logoutResponse.postValue(response)
                return@launch response
            }
            val body = RequestBody().put("plugid", user.plugId).put("token", user.token)
                .sign(user.md5Key)
            service.logout(body)
        }) {
            withContext(Dispatchers.IO) {
                appDatabase.pluginDao().deleteAll()
                appDatabase.redPocketDao().deleteAll()
            }
            logoutResponse.value = it
        }
    }
}